const express = require('express');
const app = express();
const bodyParser = require('body-parser')


// app.use(bodyParser.json({limit: '50mb'}));
// app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
app.use(bodyParser.json());
//设置跨域访问
app.all('*', function (req: any, res: any, next: any) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.listen(1088);
console.log('Listening on port 1088... 服务已启动...');

function db(data: object) {

    const mysql = require("mysql");
    const db = mysql.createConnection({
        host: "localhost",
        user: "root",
        password: "",
        database: "www_website"
    });
    db.connect((err: any) => {
        if (err) {
            console.error('MySql 连接失败 error connecting: ' + err.stack);
            return;
        }
        console.log('connected as id ' + db.threadId);
    });

    let { sql, type, connectorName, Timeout, cb }: any = data;
    db.query(sql, Timeout, (err: any, data: any) => {

        if (err) {
            return err;
        } else {

            if (cb instanceof Function) {
                cb(data);
            } else {
                app[type](connectorName, function (req: any, res: any) {

                    if (sql.includes('INSERT') || sql.includes('UPDATE') || sql.includes('DELETE')) {
                        console.log({ StatusCode: 200 })
                        res.send({ StatusCode: 200 });
                    } else {
                        console.log({ StatusCode: 200, data: data })
                        res.send({ StatusCode: 200, data: data });
                    }

                })

            }
        }

    });
    db.end((err: any) => {
        if (err) {
            console.log('关闭数据库失败：', err)
        }
        console.log('The connection is terminated now  数据库 已关闭连接')
    });
}

export { app, db }


